package com.scs.application.modules.sys.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.adapter.FlowAdapter;
import com.scs.application.modules.sys.dto.FlowDTO;
import com.scs.application.modules.sys.entity.Flow;
import com.scs.application.modules.sys.entity.FlowButton;
import com.scs.application.modules.sys.entity.FlowNode;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.properties.SystemProperties;
import com.scs.application.modules.sys.request.FlowRequest;
import com.scs.application.modules.sys.service.FlowService;
import com.scs.application.modules.sys.service.impl.FlowButtonServiceImpl;
import com.scs.application.modules.sys.service.impl.FlowNodeServiceImpl;
import com.scs.application.modules.sys.service.impl.FlowServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/flow")
public class SysFlowController {

    @Autowired
    private FlowAdapter flowAdapter;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private FlowServiceImpl flowService;


    @Autowired
    private FlowButtonServiceImpl flowButtonService;

    @Autowired
    private FlowNodeServiceImpl flowNodeService;

    /**
     * 复制流程
     *
     * @param map
     * @return
     */
    @PostMapping("/copy")
    public RestResult copy(@RequestBody Map<String, String> map) {
        String flowKey = map.get("flowKey");
        if (StringUtils.isBlank(flowKey)) {
            return RestResult.ok("复制失败");
        }
        Flow flow = flowAdapter.getFlowService().copy(flowKey);
        return RestResult.ok("复制成功", flow);
    }

    /**
     * 获取数据列表
     */
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        IPage pageResult = flowAdapter.getFlowService().page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    @GetMapping("/list")
    public RestResult<List> list() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        List result = flowAdapter.getFlowService().list(queryContext);
        return RestResult.ok("查询成功", result);
    }

    /**
     * 获取所有数据
     *
     * @param onlyBusFields 仅查询业务字段
     * @return
     */
    @GetMapping("/all")
    public RestResult findAll(@RequestParam(required = false) boolean onlyBusFields) {
        List<Flow> models = flowAdapter.getFlowService().list();
        return RestResult.ok("查询成功", models);
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Flow entity = flowAdapter.getFlowService().getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Flow entity) {
        boolean isOk = flowAdapter.getFlowService().saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        Boolean isOk = flowAdapter.getFlowService().removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        return RestResult.ok("数据删除成功");
    }

    /**
     * 获取字典比对
     *
     * @param code 获取字典比对
     * @return
     */
    @GetMapping("/diff")
    public RestResult getTwoDictTypes(@RequestParam String code) {
        FlowService fileFlowService = flowAdapter.getFlowService(false);
        if (fileFlowService.getClass().getName().equals(flowAdapter.getFlowService().getClass().getName())) {
            throw new BusinessException("产品分支不支持该功能");
        }

        HashMap<String, Object> result = new HashMap<>();
        FlowDTO fileFlowDTO = fileFlowService.getFlowDTOByCode(code);
        result.put("productFlowDTO", JSON.toJSONString(fileFlowDTO));

        FlowDTO flowDTO = flowAdapter.getFlowService().getFlowDTOByCode(code);
        result.put("projectFlowDTO", JSON.toJSONString(flowDTO));
        return RestResult.ok("获取数据成功", result);
    }

    /**
     * 同步产品视图
     *
     * @param flowRequest
     * @return
     */
    @PostMapping(value = "/sync")
    public RestResult syncFlow(@Valid @RequestBody FlowRequest flowRequest) {
        FlowService flowService = flowAdapter.getFlowService(!systemProperties.getFlagProject());
        FlowDTO flowDTO = flowService.getFlowDTOByCode(flowRequest.getCode());
        if (flowDTO == null) {
            return RestResult.error("同步数据失败,该流程可能不存在");
        }
        Flow flow = new Flow();
        BeanUtils.copyProperties(flowDTO, flow);
        flowAdapter.getFlowService().saveOrUpdate(flow);

        flowAdapter.getFlowNodeService().remove(Wrappers.<FlowNode>query().eq("flow_id", flow.getId()));
        if (flowDTO.getFlowNodes() != null && flowDTO.getFlowNodes().size() > 0) {
            flowDTO.getFlowNodes().forEach(flowNodeDTO -> {
                FlowNode flowNode = new FlowNode();
                BeanUtils.copyProperties(flowNodeDTO, flowNode);
                flowAdapter.getFlowNodeService().saveOrUpdate(flowNode);
            });
        }

        flowAdapter.getFlowButtonService().remove(Wrappers.<FlowButton>query().eq("flow_id", flow.getId()));
        if (flowDTO.getFlowButtons() != null || flowDTO.getFlowButtons().size() > 0) {
            flowDTO.getFlowButtons().forEach(flowButtonDTO -> {
                FlowButton flowButton = new FlowButton();
                BeanUtils.copyProperties(flowButtonDTO, flowButton);
                flowAdapter.getFlowButtonService().saveOrUpdate(flowButton);
            });
        }

        return RestResult.ok("同步数据成功", flowDTO);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/saveDTO")
    public RestResult saveDTO(@Valid @RequestBody FlowDTO entity) {
        Flow flow = new Flow();
        BeanUtils.copyProperties(entity, flow);
        boolean isOk = flowAdapter.getFlowService().saveOrUpdate(flow);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        if (entity.getFlowButtons() != null && !entity.getFlowButtons().isEmpty()) {
            List<FlowButton> flowButtons = Lists.newArrayList();
            for (FlowDTO.FlowButtonDTO flowButtonDTO : entity.getFlowButtons()) {
                FlowButton flowButton = new FlowButton();
                BeanUtils.copyProperties(flowButtonDTO, flowButton);
                flowButton.setFlowId(flow.getId());
                flowButtons.add(flowButton);
            }
            flowAdapter.getFlowButtonService().saveOrUpdateBatch(flowButtons);
        }

        if (entity.getFlowNodes() != null && !entity.getFlowNodes().isEmpty()) {
            List<FlowNode> flowNodes = Lists.newArrayList();
            for (FlowDTO.FlowNodeDTO flowNodeDTO : entity.getFlowNodes()) {
                FlowNode flowNode = new FlowNode();
                BeanUtils.copyProperties(flowNodeDTO, flowNode);
                flowNode.setFlowId(flow.getId());
                flowNodes.add(flowNode);
            }
            flowAdapter.getFlowNodeService().saveOrUpdateBatch(flowNodes);
        }
        return RestResult.ok("数据保存成功", entity);
    }

    // 流程配置
    @GetMapping(value = "/listMapShow")
    public RestResult listShow() {
        List<Flow> flowList = flowService.list();
        Map<String,List<FlowNode>> flowNodeMapByFlowId = flowNodeService.list().stream().collect(Collectors.groupingBy(FlowNode::getFlowId));
        Map<String,List<FlowButton>> flowButtonMapByFlowId = flowButtonService.list().stream().collect(Collectors.groupingBy(FlowButton::getFlowId));
        if (flowList != null || flowList.size() != 0) {
            flowList.stream().forEach(flow -> {
                if (flowNodeMapByFlowId.containsKey(flow.getId())) {
                    flow.setFlowNodeList(flowNodeMapByFlowId.get(flow.getId()));
                }
                if (flowButtonMapByFlowId.containsKey(flow.getId())) {
                    flow.setFlowButtonList(flowButtonMapByFlowId.get(flow.getId()));
                }
            });
        }
        return RestResult.ok("获取流程配置成功！", flowList.stream().collect(Collectors.toMap(Flow::getCode, t -> t)));
    }
}
